using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 模型转换服务：外部工具编排（Python 脚本），不内置第三方代码，规避版权风险
    /// </summary>
    public class ModelConversionService : IModelConversionService
    {
        public async Task<bool> ConvertToOnnxAsync(string inputPath, string outputPath, string pythonExe, string scriptPath, string extraArgs = "")
        {
            var args = $"\"{scriptPath}\" --input \"{inputPath}\" --output \"{outputPath}\" {extraArgs}".Trim();
            return await RunPythonAsync(pythonExe, args);
        }

        public async Task<bool> ConvertToCppFormatAsync(string inputPath, string outputPath, string pythonExe, string scriptPath, string format, string extraArgs = "")
        {
            var args = $"\"{scriptPath}\" --input \"{inputPath}\" --output \"{outputPath}\" --format {format} {extraArgs}".Trim();
            return await RunPythonAsync(pythonExe, args);
        }

        private static async Task<bool> RunPythonAsync(string pythonExe, string args)
        {
            var psi = new ProcessStartInfo
            {
                FileName = pythonExe,
                Arguments = args,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };
            try
            {
                using var p = Process.Start(psi);
                if (p == null) return false;
                string stdout = await p.StandardOutput.ReadToEndAsync();
                string stderr = await p.StandardError.ReadToEndAsync();
                await p.WaitForExitAsync();
                return p.ExitCode == 0;
            }
            catch
            {
                return false;
            }
        }
    }
}

